import {getInfo, login, loginOut} from '@/api/base/user.js'
import {getToken, setToken, removeToken, removeLocalStore} from '@/utils/hongUtils'

const user = {
    namespaces:true,
    state: {
        loginUser: {},//登录信息
        permission: [],//权限
    },
    getters: {},
    mutations: {
        //设置用户信息
        SET_LOGIN_USER: (state, data) => {
            state.loginUser = data
        },
        //设置权限
        SET_PERMISSION: (state, data) => {
            state.permission = data
        },

    },
    actions: {
        //获取登录信息
        loginInfo({commit},data) {
            return new Promise((resolve, reject) => {
                console.log("data==>",data);
                login(data).then(res => {
                    let data = res.data;
                    setToken(data);//设置token
                    resolve();//成功回调
                }).catch(e => {
                    console.error("登录失败", e);
                    reject(e);
                })
            })
        },

        //获取登录信息
        getLoginuser({commit}) {
            return new Promise((resolve, reject) => {

                getInfo().then(res => {
                    let data = res.data;
                    let loginUser = data.loginUser;//登录信息
                    let permission = data.permission;///权限
                    commit("SET_LOGIN_USER", loginUser);//登录信息
                    commit("SET_PERMISSION", permission);//权限
                    console.log("获取权限==》",permission)
                    resolve();

                }).catch(e => {
                    console.error("获取登录信息错误", e);
                    reject();
                })
            })
        },
        //退出登录
        loginuUserOut({commit}) {
            return new Promise((resolve, reject) => {
                loginOut().then(res => {
                    if (!(res && res.code == 200)) {
                        console.error("退出登录失败")
                        reject();//失败返回
                    }
                    //清空
                    commit("SET_LOGIN_USER", {});//登录信息
                    commit("SET_PERMISSION", []);//权限
                    commit("REMOVE_ALL_INTERVIEW");//权限
                    // promission
                    removeLocalStore('currentShow');//移除选中
                    removeLocalStore('interview');//移除标签
                    removeToken();//移除token
                    resolve();//成功返回
                }).catch(e => {
                    console.error("获取登录信息错误", e);
                    reject();//失败返回
                })
            })
        }
    },

}
export default user